package com.rfid.project.web;

import java.text.DateFormat;
import java.util.Calendar;
import java.util.List;
import java.io.NotActiveException;
import java.util.Date;

import javassist.NotFoundException;

import javax.naming.NotContextException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.ui.Model;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springframework.data.domain.Page;

import biz.util.IdUtil;
import biz.appframe.PageJsonBean;

import com.rfid.project.exception.CannotDelException;
import com.rfid.project.exception.CannotUpdateException;
import com.rfid.project.model.Authority;
import com.rfid.project.model.People;
import com.rfid.project.model.PublicNotice;
import com.rfid.project.service.AuthorityService;
import com.rfid.project.service.InboxService;
import com.rfid.project.service.PeopleService;
import com.rfid.project.service.PositionAuthorityService;
import com.rfid.project.service.Process;
import com.rfid.project.service.ProcessEngine;
import com.rfid.project.service.ProcessStatus;
import com.rfid.project.service.ProjectTaskPersonService;
import com.rfid.project.service.PublicNoticeService;
import com.rfid.project.model.Department;
import com.rfid.project.service.DepartmentService;
import com.rfid.project.model.Position;
import com.rfid.project.service.PositionService;
import com.rfid.project.model.TechnicalTitle;
import com.rfid.project.service.TechnicalTitleService;

@Controller
public class PeopleController {

	private static final Logger logger = LoggerFactory
			.getLogger(PeopleController.class);

	@Autowired
	private PeopleService peopleService;

	@Autowired
	private DepartmentService departmentService;

	@Autowired
	private PositionService positionService;

	@Autowired
	private TechnicalTitleService technicalTitleService;

	@Autowired
	private PositionAuthorityService positionAuthorityService;

	@Autowired
	private AuthorityService authorityService;

	@Autowired
	private ProcessEngine processEngine;

	@Autowired
	private ProjectTaskPersonService projectTaskPersonService;

	@Autowired
	private InboxService inboxService;
	
	@Autowired
	private PublicNoticeService publicNoticeService;

	@RequestMapping(value = "/peopleAnalyse")
	public String peopleAnalyse(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		return "peopleAnalyse";
	}

	@RequestMapping(value = "/login")
	public String login(HttpServletRequest request,
			HttpServletResponse response,
			@Valid People people, Model model,
			RedirectAttributes redirectAttributes) {
		request.removeAttribute("msg");
		HttpSession session = request.getSession();
		session.removeAttribute("currentUser");
		session.removeAttribute("powers");
		if (null == people || null == people.getUsername()) {
			return "login";
		}
		try {
			People currentUser = this.peopleService.login(people);
			List<Authority> powers = null;
			if(currentUser.getId() != 0){
				powers = this.positionAuthorityService.findAuthorityByPosition(currentUser.getPosition());
				if (powers.isEmpty()) {
					throw new NotActiveException("用户无任何权限！");
				}
			}else{
				powers = this.authorityService.findAll();
			}
			session.setAttribute("currentUser", currentUser);
			session.setAttribute("powers", powers);
			return "redirect:/index";
		} catch (NotContextException e) {
			model.addAttribute("username", people.getUsername());
			model.addAttribute("msg", e.getMessage());
		} catch (NotFoundException e) {
			model.addAttribute("msg", e.getMessage());
		} catch (NotActiveException e) {
			model.addAttribute("msg", e.getMessage());
		}
		return "login";
	}
	
	@RequestMapping(value = "/loginout")
	public String loginout(HttpServletRequest request,
			HttpServletResponse response,
			@Valid People people, Model model,
			RedirectAttributes redirectAttributes) {
		request.removeAttribute("msg");
		HttpSession session = request.getSession();
		session.removeAttribute("currentUser");
		session.removeAttribute("powers");
		return "redirect:/";
	}

	//返回人员管理界面
	@RequestMapping(value = "/peoplemgr")
	public String peoplemgr(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		List<Department> departments = departmentService.findAll();
		model.addAttribute("departments", departments);

		List<Position> positions = positionService.findAll();
		model.addAttribute("positions", positions);

		List<TechnicalTitle> technicalTitles = technicalTitleService.findAll();
		model.addAttribute("technicalTitles", technicalTitles);
		return "peoplemgr";
	}
	
	@RequestMapping(value = "/myProfile")
	public String myProfile(HttpServletRequest request,
			HttpServletResponse response, Model model) {
		
		People currentUser = (People) request.getSession().getAttribute("currentUser");
		if (currentUser==null) {
			return null;
		}
		List<Department> departments = departmentService.findAll();
		model.addAttribute("departments", departments);

		List<Position> positions = positionService.findAll();
		model.addAttribute("positions", positions);

		List<TechnicalTitle> technicalTitles = technicalTitleService.findAll();
		model.addAttribute("technicalTitles", technicalTitles);
		return "myProfile";
	}

	@RequestMapping(value = "/awaitAdvices")
	public String awaitAdvices(HttpServletRequest request,
			HttpServletResponse response, Model model){
		People currentUser = (People)request.getSession().getAttribute("currentUser");
		//待审批业务个数
		List<Process> processes = processEngine.getCurrentTaskList(null, null, currentUser);
		if(null != processes && !processes.isEmpty()){
			model.addAttribute("processes", processes.size());
		}
		//未查看的消息个数
		Long novelMessages = inboxService.findCount(currentUser.getId(), null, null, null, null, ProcessStatus.NEW);
		if (IdUtil.isNotEmpty(novelMessages) && novelMessages > 0) {
			model.addAttribute("novelMessages", novelMessages);
		}
		//未领取的任务个数
		Long novelProjectTasks = projectTaskPersonService.findAllCount(null, null, null, currentUser.getId(), ProcessStatus.NOVEL, null, null);
		if (IdUtil.isNotEmpty(novelProjectTasks) && novelProjectTasks > 0) {
			model.addAttribute("novelProjectTasks", novelProjectTasks);
		}
		//未完成的任务个数
		Long workingProjectTasks = projectTaskPersonService.findAllCount(null, null, null, currentUser.getId(), ProcessStatus.WORKING, null, null);
		if (IdUtil.isNotEmpty(workingProjectTasks) && workingProjectTasks > 0) {
			model.addAttribute("workingProjectTasks", workingProjectTasks);
		}
		//公告
		List<PublicNotice> publicNotices = this.publicNoticeService.findNew();
		model.addAttribute("publicNotices", publicNotices);
		
		Calendar cal = Calendar.getInstance();
		cal.add(Calendar.DAY_OF_MONTH, -5);
		model.addAttribute("newDate", cal.getTime());
		return "home";
	}
	
	@RequestMapping(value = "/queryMyProfile")
	public String queryMyProfile(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "personalTel", defaultValue = "") String personalTel,
			@RequestParam(value = "departmentId", defaultValue = "-1") Long departmentId,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "officeTel", defaultValue = "") String officeTel,
			@RequestParam(value = "remark", defaultValue = "") String remark,
			@RequestParam(value = "positionId", defaultValue = "-1") Long positionId,
			@RequestParam(value = "technicalTitleId", defaultValue = "-1") Long technicalTitleId,
			@RequestParam(value = "username", defaultValue = "") String username,
			@RequestParam(value = "password", defaultValue = "") String password,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model){
		Page<People> peoples = peopleService.findMyProfile(id, name, personalTel,
				departmentId, gender, officeTel, remark, positionId,
				technicalTitleId, username, password, pageNumber, pageSize,
				sort, order);
		JSONObject object = new JSONObject();
		object.put("total", peoples.getTotalElements());
		JSONArray models = new JSONArray();
		for (People people : peoples) {
			JSONObject mod = new JSONObject();
			wrapData(people, mod);

			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	@RequestMapping(value = "/queryPeople")
	public String queryPeople(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "name", defaultValue = "") String name,
			@RequestParam(value = "personalTel", defaultValue = "") String personalTel,
			@RequestParam(value = "departmentId", defaultValue = "-1") Long departmentId,
			@RequestParam(value = "gender", defaultValue = "") String gender,
			@RequestParam(value = "officeTel", defaultValue = "") String officeTel,
			@RequestParam(value = "remark", defaultValue = "") String remark,
			@RequestParam(value = "positionId", defaultValue = "-1") Long positionId,
			@RequestParam(value = "technicalTitleId", defaultValue = "-1") Long technicalTitleId,
			@RequestParam(value = "username", defaultValue = "") String username,
			@RequestParam(value = "password", defaultValue = "") String password,
			@RequestParam(value = "page", defaultValue = "1") Integer pageNumber,
			@RequestParam(value = "rows", defaultValue = "10") Integer pageSize,
			@RequestParam(value = "sort", defaultValue = "") String sort,
			@RequestParam(value = "order", defaultValue = "") String order,
			Model model){
		Page<People> peoples = peopleService.findAll(name, personalTel,
				departmentId, gender, officeTel, remark, positionId,
				technicalTitleId, username, password, pageNumber, pageSize,
				sort, order);
		JSONObject object = new JSONObject();
		object.put("total", peoples.getTotalElements());
		JSONArray models = new JSONArray();
		for (People people : peoples) {
			JSONObject mod = new JSONObject();
			wrapData(people, mod);

			models.add(mod);
		}
		object.put("rows", models);
		PageJsonBean.printObject(response, object);
		return null;
	}
	
	@RequestMapping(value = "/findPeople")
	public String findPeople(
			HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			Model model){
		People people = peopleService.findOne(id);
		JSONObject object = new JSONObject();
		JSONObject mod = new JSONObject();
		wrapData(people, mod);
		object.put("success", true);
		object.put("data", mod);
		PageJsonBean.printObject(response, object);
		return null;
	}

	private void wrapData(People people, JSONObject mod) {
		mod.put("id", people.getId());
		mod.put("name", people.getName());
		mod.put("personalTel", people.getPersonalTel());
		mod.put("departmentId", people.getDepartment().getId());
		mod.put("departmentName", people.getDepartment().getName());
		mod.put("gender", people.getGender());
		mod.put("officeTel", people.getOfficeTel());
		mod.put("remark", people.getRemark());
		mod.put("positionId", people.getPosition().getId());
		mod.put("positionName", people.getPosition().getName());
		mod.put("technicalTitleId", people.getTechnicalTitle().getId());
		mod.put("technicalTitleName", people.getTechnicalTitle().getName());
		mod.put("username", people.getUsername());
		mod.put("password", people.getPassword());
	}
	
	@RequestMapping(value = "/editPeople", method = RequestMethod.POST)
	public String editPeople(HttpServletRequest request,
			HttpServletResponse response,
			@Valid People people, Model model,
			RedirectAttributes redirectAttributes) {
		JSONObject result = new JSONObject();
		boolean	flag = true;
		try {
			this.peopleService.savePeople(people);;
		} catch (CannotDelException e) {
			flag = false;
			result.put("msg",e.getMessage());
		}
		
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/editMyProfile", method = RequestMethod.POST)
	public String editMyProfile(HttpServletRequest request,
			HttpServletResponse response,
			@Valid People people, Model model,
			RedirectAttributes redirectAttributes) {
		JSONObject result = new JSONObject();
		boolean	flag = true;
		People currentUser = (People) request.getSession().getAttribute("currentUser");
		currentUser.setPersonalTel(people.getPersonalTel());
		currentUser.setOfficeTel(people.getOfficeTel());
		currentUser.setRemark(people.getRemark());
		try {
			this.peopleService.savePeople(currentUser);;
		} catch (CannotDelException e) {
			flag = false;
			result.put("msg",e.getMessage());
		}
		
		request.getSession().setAttribute("currentUser", currentUser);
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/changePwd", method = RequestMethod.POST)
	public String changePwd(HttpServletRequest request,
			HttpServletResponse response,
			Model model,
			RedirectAttributes redirectAttributes,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			@RequestParam(value = "password", defaultValue = "") String password) {
		JSONObject result = new JSONObject();
		boolean	flag = true;
		try {
			this.peopleService.changePwd(id, password);
			People currentUser = (People) request.getSession().getAttribute("currentUser");
			currentUser.setPassword(password);
			request.getSession().setAttribute("currentUser", currentUser);	
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg",e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/resetPwd", method = RequestMethod.POST)
	public String resetPwd(HttpServletRequest request,
			HttpServletResponse response,
			Model model,
			RedirectAttributes redirectAttributes,
			@RequestParam(value = "id", defaultValue = "-1") Long id,
			@RequestParam(value = "password", defaultValue = "") String password) {
		JSONObject result = new JSONObject();
		boolean	flag = true;
		try {
			this.peopleService.changePwd(id, password);
		} catch (CannotUpdateException e) {
			flag = false;
			result.put("msg",e.getMessage());
		}
		result.put("success", flag);
		PageJsonBean.printObject(response, result);
		return null;
	}
	
	@RequestMapping(value = "/delPeople")
	public String delAuthority(HttpServletRequest request,
			HttpServletResponse response,
			@RequestParam(value = "id", defaultValue = "") Long id) {
		this.peopleService.deletePeople(id);
		JSONObject result = new JSONObject();
		result.put("success", true);
		PageJsonBean.printObject(response, result);
		return null;
	}

	@InitBinder
	protected void initBinder(HttpServletRequest request,
			ServletRequestDataBinder binder) throws Exception {
		DateFormat dateFormat = com.rfid.project.util.DateUtil.getFormat();
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true));
	}

}
